package com.zg.datapush.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.common.core.dao.datapush.dao.DpPushLogDao;
import com.zg.common.core.dao.datapush.entity.DpPushLog;
import com.zg.datapush.vo.DpPushLogVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 推送日志详情服务
 * @author zg
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DpPushLogService {

    private final DpPushLogDao pushLogDao;

    /**
     * 根据推送记录ID查询日志详情
     */
    public List<DpPushLogVo> listByRecordId(Long recordId) {
        List<DpPushLog> entities = pushLogDao.list(
            new LambdaQueryWrapper<DpPushLog>()
                .eq(DpPushLog::getRecordId, recordId)
                .orderByAsc(DpPushLog::getStepOrder)
        );

        return entities.stream()
            .map(entity -> {
                DpPushLogVo vo = new DpPushLogVo();
                BeanUtil.copyProperties(entity, vo);
                return vo;
            }).collect(Collectors.toList());
    }

    /**
     * 创建推送日志
     */
    public DpPushLog createLog(Long recordId, String stepName, Integer stepOrder,
                               String className, String methodName) {
        DpPushLog log = new DpPushLog();
        log.setRecordId(recordId);
        log.setStepName(stepName);
        log.setStepOrder(stepOrder);
        log.setClassName(className);
        log.setMethodName(methodName);
        log.setStartTime(new Timestamp(System.currentTimeMillis()));
        log.setStatus("running");
        pushLogDao.save(log);
        return log;
    }

    /**
     * 更新日志为成功状态
     */
    public void updateLogSuccess(Long logId, Object inputData, Object outputData) {
        DpPushLog log = pushLogDao.getById(logId);
        if (log != null) {
            log.setEndTime(new Timestamp(System.currentTimeMillis()));
            log.setDuration(log.getEndTime().getTime() - log.getStartTime().getTime());
            log.setStatus("success");

            if (inputData != null) {
                log.setInputData(JSONUtil.toJsonStr(inputData));
            }
            if (outputData != null) {
                log.setOutputData(JSONUtil.toJsonStr(outputData));
            }

            pushLogDao.updateById(log);
        }
    }

    /**
     * 更新日志为失败状态
     */
    public void updateLogFailed(Long logId, Object inputData, Exception exception) {
        DpPushLog log = pushLogDao.getById(logId);
        if (log != null) {
            log.setEndTime(new Timestamp(System.currentTimeMillis()));
            log.setDuration(log.getEndTime().getTime() - log.getStartTime().getTime());
            log.setStatus("failed");

            if (inputData != null) {
                log.setInputData(JSONUtil.toJsonStr(inputData));
            }

            if (exception != null) {
                log.setErrorMessage(exception.getMessage());
                log.setStackTrace(getStackTrace(exception));
            }

            pushLogDao.updateById(log);
        }
    }

    /**
     * 获取异常堆栈信息
     */
    private String getStackTrace(Exception exception) {
        if (exception == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        sb.append(exception.getClass().getName()).append(": ").append(exception.getMessage()).append("\n");

        for (StackTraceElement element : exception.getStackTrace()) {
            sb.append("\tat ").append(element.toString()).append("\n");
        }

        // 限制堆栈信息长度，避免过长
        String stackTrace = sb.toString();
        if (stackTrace.length() > 5000) {
            stackTrace = stackTrace.substring(0, 5000) + "...(truncated)";
        }

        return stackTrace;
    }
}
